#include "stdio.h"
#include "stdlib.h"
typedef struct Node
{
    int data;
    struct Node *next;
    /* data */
}Node;

Node *create_list (int data[], size_t count) {
    Node *head = NULL;
    Node *tail = NULL;
    if ((!data) || (count == 0))
        goto out;
    for (size_t i = 0; i < count; i++)
    {
        Node *new_node = (Node *)malloc(sizeof(Node));
        if (!new_node)
        {
            goto out;
            /* code */
        }
        new_node->data = data[i];
        new_node->next = NULL;

        if (!head) {
            head = new_node;
            head->next = NULL;
        }
        if (!tail) {
            tail = new_node;
            tail->next = NULL;
        }
        tail->next = new_node;
        tail = new_node;
    }
    return head;
out:
    return NULL;
}
int destroy_list(Node *head){
    if (!head)
        return 0;
    Node *current = head;
    Node *next = NULL;
    while (current)
    {
        next = current->next;
        free(current);
        current = NULL;
        current = next;
    }
    return 0;
}
int print_list(Node *head) {
    struct Node* current = head;
    while (current != NULL) {
        printf("%d ", current->data);
        current = current->next;
    }
    printf("\n");
}
int list_insert(Node *head , int position, int a)
{
    Node *new_node = (Node *)malloc(sizeof(Node));
    if (!new_node)
    {
        goto out;
    }
    new_node->data = a;
    new_node->next = NULL;

    struct Node* current = head;
    struct Node* next = NULL;
    int index = 1;
    while (current->next != NULL && index < position) {
        current = current->next;
        index++;
    }
    //index = position
    new_node->next = current->next;
    current->next = new_node;
    return 0;
out:
    return -1;
}
// 在链表中查询节点
Node* list_search(Node* head, int value) {
    struct Node* current = head;
    while (current != NULL) {
        if (current->data == value) {
            return current;  // 返回匹配的节点地址
        }
        current = current->next;
    }
    return NULL;  // 若没有找到匹配节点，则返回NULL
}
int main() {
    int a[5]={1,2,3,4,5};
    Node *list = create_list(a, 5);
    // list_delete();
    // list_search();
    // list_update();
    // print_list(list);
    list_search(list, 1);
    print_list(list);
    list_insert(list, 2, 1);
    print_list(list);
    destroy_list(list);
}